#include "SendHeartRequset.h"
#include "CurlRequestUtil.h"
#include <glib.h>
#include <stdio.h>
#include <curl/curl.h>
#include <cjson/cJSON.h>
#include "AdDao.h"
#include "AdParesLogic.h"

// 解析命令列表
void parseCmdList(cJSON* cmdListJson){
    if(cJSON_IsArray(cmdListJson)){
        int size = cJSON_GetArraySize(cmdListJson);
        for (int i = 0; i < size; i++)
        {
            cJSON* cmdJson = cJSON_GetArrayItem(cmdListJson,i);
            if(cJSON_IsNumber(cmdJson)){
                int num = cmdJson->valueint;
                switch (num){
                case 1:
                    printf("关机命令\n");
                    break;
                case 2:
                    printf("重启命令\n");
                    break;
                default:
                    break;
                }
            }
        }
    }
}

// 解析cjson转为Ad结构体，并返回
Ad* parseUpDownSplitScr(cJSON* adJson)
{
    Ad* result = (Ad*)calloc(1,sizeof(Ad));
    if (cJSON_IsObject(adJson))
    {
        //自己的一些属性解析
        cJSON *idJson = cJSON_GetObjectItemCaseSensitive(adJson,"id");
        int id = idJson->valueint;
        cJSON *templateIdJson = cJSON_GetObjectItemCaseSensitive(adJson,"template_id");
        int templateId = templateIdJson->valueint;
        cJSON *customerIdJson = cJSON_GetObjectItemCaseSensitive(adJson,"customer_id");
        int customerId = customerIdJson->valueint;
        cJSON *startTimeJson = cJSON_GetObjectItemCaseSensitive(adJson,"start_time");
        char *startTime = startTimeJson->valuestring;
        cJSON *endTimeJson = cJSON_GetObjectItemCaseSensitive(adJson,"end_time");
        char *endTime = endTimeJson->valuestring;
        int state = cJSON_GetObjectItemCaseSensitive(adJson,"state")->valueint;

        result->id  = id;
        result->template_id  = templateId;
        result->customer_id  = customerId;
        result->start_time  = startTime;
        result->end_time  = endTime;
        result->state = state;
        //AdResource *resources[3];

        //广告资源解析
        AdResource *upAr = (AdResource*)calloc(1,sizeof(AdResource));
        upAr->ad_id = id;
        upAr->index = 0;
        cJSON *typeIdJson = cJSON_GetObjectItemCaseSensitive(adJson,"top_media_type_id");
        int typeId = typeIdJson->valueint;
        upAr->type_id = typeId;
        cJSON *urlJson = cJSON_GetObjectItemCaseSensitive(adJson,"top_media_url");
        char *url = urlJson->valuestring;
        upAr->path = url;
        cJSON *signJson = cJSON_GetObjectItemCaseSensitive(adJson,"top_media_sign");
        char *sign = signJson->valuestring;
        upAr->sign = sign;

        result->resources[0] =upAr;

        AdResource *buttomAr = (AdResource*)calloc(1,sizeof(AdResource));
        buttomAr->ad_id = id;
        buttomAr->index = 0;
        cJSON *typeIdJson1 = cJSON_GetObjectItemCaseSensitive(adJson,"buttom_media_type_id");
        int typeId1 = typeIdJson1->valueint;
        buttomAr->type_id = typeId1;
        cJSON *urlJson1 = cJSON_GetObjectItemCaseSensitive(adJson,"buttom_media_url");
        char *url1 = urlJson1->valuestring;
        buttomAr->path = url1;
        cJSON *signJson1 = cJSON_GetObjectItemCaseSensitive(adJson,"buttom_media_sign");
        char *sign1 = signJson1->valuestring;
        buttomAr->sign = sign1;

        result->resources[1] =buttomAr;
    }
    return result;
}

// 解析广告列表
void parseAdList(cJSON* adList){
    if(cJSON_IsArray(adList)){
        int size = cJSON_GetArraySize(adList);
        Ad* ads[size];
        for (int i = 0; i < size; i++)
        {
            cJSON* item = cJSON_GetArrayItem(adList,i);
            int templateId = cJSON_GetObjectItemCaseSensitive(item,"template_id")->valueint;
            switch (templateId)
            {
            case 1:
                printf("全屏展示\n");
                break;
            case 2:
                printf("左右展示\n");
                break;
            case 6:  // 上下展示
                Ad* ad = parseUpDownSplitScr(item);
                ads[i] = ad;
                break;
            default:
                break;
            }
        }

        // 下载并生成本地广告列表保存到数据库
        // 遍历所有广告进行下载和保存播放列表。
        for (int i = 0; i < size; i++)
        {
            Ad *ad =  ads[i];
            g_print("adid=%d\n",ad->id);
            for (int i = 0; i < 3; i++)
            {
                AdResource *ar = ad->resources[i];
                if (ar!=NULL)
                {
                    g_print("url=%s\n",ar->path);
                }
            }
        }
        // 下载并生成本地广告列表保存到sqlite数据库
        int result = downloadAdsAndGenLocalAdListToSqlite(ads,size);
    }
}


size_t heartsWriteCallback(void *contents, size_t size, size_t nmemb, void *userp) {
    size_t realsize = size * nmemb;
    // 这里可以处理获取到的数据，比如存储到文件或者其他操作
    char * result = (char *)contents;

    // result就是url地址响应回来的一个信息，这个信息一般都是一个json格式的字符串
    // 所以这个地方要利用cJSONqu解析json字符串
    cJSON* root = cJSON_Parse(result);  // 将json字符串转成json对象
    if(root != NULL)
    {
        cJSON* successJson = cJSON_GetObjectItemCaseSensitive(root,"success");
        cJSON* codeJson = cJSON_GetObjectItemCaseSensitive(root,"code");
        cJSON* messageJson = cJSON_GetObjectItemCaseSensitive(root,"message");

        if(successJson->valueint == 1 && codeJson->valueint == 200)
        {
            printf("广告机心跳请求成功!\n");
            cJSON* dataJson = cJSON_GetObjectItemCaseSensitive(root,"data");
            if(dataJson != NULL){
                cJSON* adListJson = cJSON_GetObjectItemCaseSensitive(dataJson,"ad_list");
                cJSON* cmdListJson = cJSON_GetObjectItemCaseSensitive(dataJson,"cmd_list");

                if(cmdListJson != NULL){
                    // 解析命令列表
                    parseCmdList(cmdListJson);
                }

                if(adListJson != NULL){
                    parseAdList(adListJson);
                }
            }
        }
        else{
            printf("广告机心跳请求失败!原因=%s\n",messageJson->valuestring);
        }
    }

    return realsize;
}

// 发送心跳请求
void sendHeartRequest(char* gatewayIp, char* sn){
    // 使用glib把数据保存到ini配置文件中
    // 改造一下，读取配置文件，获取设备文件路径
    GKeyFile *file = g_key_file_new();
    g_key_file_load_from_file(file,"../config/config.ini",G_KEY_FILE_NONE,NULL);
    gchar* path = g_key_file_get_string(file,"config","deviceInfoPath",NULL);


    GKeyFile *keyFile = g_key_file_new();
    g_key_file_load_from_file(keyFile,path,G_KEY_FILE_NONE,NULL);
    gatewayIp = g_key_file_get_string(keyFile,"config","gatewayIp",NULL);
    char* location = g_key_file_get_string(keyFile,"config","location",NULL);

    g_key_file_free(keyFile);
    g_key_file_free(file);

    char* urlFormatStr = "http://%s/hearts.json?sn=%s";
    char* url = (char*)calloc(1,100);

    // 构造url  
    sprintf(url,urlFormatStr,gatewayIp,sn);
    printf("config url: %s\n",url);
    sendGetRequest(url,heartsWriteCallback);
}